package com.merry.api.validator;

import com.merry.api.constant.ApiConstant;
import com.merry.api.entity.ApiPermissionEntity;
import com.merry.api.mapper.ApiMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * API接口的权限校验器
 */
@Service
@Order(2)
public class ApiAuthorityValidator implements ApiValidator {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private ApiMapper mapper;

    /**
     * 权限验证方法
     */
    @Override
    @SuppressWarnings("unchecked")
    public boolean verify(HttpServletRequest request) throws Exception {
        String paasId = request.getHeader(ApiConstant.PASSID);
        // 根据paasid获取对应的token及用户信息
        List<ApiPermissionEntity> apiUser = (List<ApiPermissionEntity>) redisTemplate.boundHashOps(ApiConstant.REDIS_KEY_API_PERMISSION).get(paasId);
        String url = request.getServletPath();
        if (apiUser == null || apiUser.size()==0) {
            apiUser = mapper.queryPermissionByUserId(paasId);
            if (apiUser != null && apiUser.size() != 0) {
                redisTemplate.boundHashOps(ApiConstant.REDIS_KEY_API_PERMISSION).put(paasId, apiUser);
            }
        }
        if (apiUser==null || apiUser.size()==0) {
            throw new Exception("没有权限");
        }
        for (ApiPermissionEntity u : apiUser) {
            if (StringUtils.isNotEmpty(u.getUrl()) && process(u, url)) {
                return true;
            }
        }
        throw new Exception("没有权限！");
    }

    /**
     * 处理权限验证
     */
    private boolean process(ApiPermissionEntity apiPermissionEntity, String url) throws Exception {
        if (StringUtils.equals(apiPermissionEntity.getUrl(), url)) {
            if (apiPermissionEntity.getEffectiveDate() != null && System.currentTimeMillis() > apiPermissionEntity.getEffectiveDate().getTime()) {
                throw new Exception("授权已经过期了！");
            }
            return true;
        }
        return false;
    }
}
